<?php
/**
 * This class uses cURL to load a RSS feed and passes the xml to simplexml which creates object of the recived XML.
 * @author Jarmo Baltzar
 * @author Viktor Karlsson
 * @version 1.0
 */
	
	class Scraping implements iScraping
	{
		
		private $m_url = NULL;
		
		/**
		 * 
		 * This method sets the URL to private $m_url, if the URL is correct and passes regexp controll.
		 * 
		 * @name setUrl
		 * @return none
		 */
		public function setUrl($url)
		{	
			if(preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url))
			{
				$this->m_url = $url;
			}
		}
		
		/**
		 * 
		 * This method returns the URL that has been set by setUrl. 
		 * Used mainly for testing purposes.
		 * 
		 * @name getUrl
		 * @return Returns the URL that setUrl method has set.
		 */
		public function getUrl()
		{
			return $this->m_url;
		}
		
		/**
		 * 
		 * This medhod gets URL from the private memeber and loads the URL with cURL. Once it's loaded and has a response
		 * simplexml will create an object that will be returned to the caller.
		 * 
		 * Example how to call retriveXml from Controller.
		 * <code>
		 * <?php
		 * $scraping = new Scraping();
		 * $result = $scraping->retriveXml();
		 * ?>
		 * </code>
		 * 
		 * @name retriveXml
		 * @return xml object
		 */
		public function retriveXml()
		{
			$bool = false;
			
			// Use a component to retrive xml with, we use curl here
			$result = Curl::retriveWithCurl($this->m_url);
			
     		// Check if valid
     		if($result != null && $result != '')
     		{
     			$bool = $this->isValidXml($result);
     		}
    		
     		// If valid load xml
     		if($bool == true)
     		{
     			$xml = @simplexml_load_string($result);
     		    if($xml)
	        	{
	        		$doc = new SimpleXmlElement($result, LIBXML_NOCDATA);
	        		return $doc;
	        	}
     		}
			return null;
		}
		
		/**
		 * 
		 * This method takes the xml and checks for errors
		 * @name isValidXml
		 * @param $xml
		 * @return boolean true or false
		 */
		private function isValidXml($xml)
		{
			libxml_use_internal_errors(true);
			
			$doc = new DOMDocument("1.0", "utf-8");
			$doc->loadXML($xml);
			
			$errors = libxml_get_errors();
			return empty($errors);
		}
	}